package NewTmas.FramesandPanels;

import NewTmas.Listeners.LogPeriodicRefreshListener;
import com.toedter.calendar.JDateChooser;
import taskmaster.controller.ViewTasks;
import taskmaster.util.JSearchableTextArea;

import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;


/**
 * Created by IntelliJ IDEA.
 * User: abhatnag
 * Date: 6/29/11
 * Time: 11:32 AM
 * To change this template use File | Settings | File Templates.
 */


/* Remember to set the System Properties as -DTMS_LOGDIR="Q:\data\tms\logs" to get the LogFilePath*/
public class LogFileFrame
{


    String task, job;

    Date date;
    JDesktopPane dtp;
    JInternalFrame logFrame;
    JTextField urlField;
    JTextArea textArea ;
    GraphicsEnvironment ge;
    JComboBox fonts;
    JDateChooser dateChooser =new JDateChooser() ;


    public LogFileFrame(String jobName, String task, Date date,JDesktopPane desktopPane)
    {

        this.job = jobName;
        this.date = date;
        this.task = task;
        this.dtp = desktopPane;
        this.logFrame=new JInternalFrame("LOG : "+task+":"+jobName);
        this.textArea = new JSearchableTextArea();
        this.urlField = new JTextField();

        logFrame.setVisible(true);

        textArea.setFont(new Font("DialogInput", Font.PLAIN, 12));

        String path;
        logFrame.setSize(500, 525);

        logFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);



        JMenuBar menuBar=new JMenuBar();
        JMenu actions=new JMenu("Actions");
        menuBar.add(actions);
        logFrame.setMenuBar(menuBar);
        JButton  refreshOnce = new JButton("Refresh");
        JMenu refreshMenu=new JMenu("Refresh Every");


        int[] timeInterval=new int[]{30,60,600,3600};                       //time interval in seconds
        final ActionListener refreshtimer=new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                refreshLog();
            }
        } ;
        for(int i=0;i<timeInterval.length;i++)
        {
            String suffix=new String();

            if(timeInterval[i]<60) {
                suffix=String.valueOf(timeInterval[i]) +" s" ;
            }

            if(timeInterval[i]>=60 && timeInterval[i]<3600)
            {
                int minutes=  ((timeInterval[i]/60) % 60);
                suffix=String.valueOf(minutes) +" min" ;

            }

            if(timeInterval[i]>=3600){
                int hours=(timeInterval[i]/3600) % 24;
                suffix=String.valueOf(hours) +" hr" ;
            }
            final JCheckBoxMenuItem refreshEvery = new JCheckBoxMenuItem(suffix);
            refreshEvery.addItemListener(new LogPeriodicRefreshListener(refreshtimer,timeInterval[i]*1000));
            refreshMenu.add(refreshEvery);
        }

        actions.add(refreshMenu );


        refreshOnce.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                refreshLog();
            }
        });



        logFrame.setIconifiable(true);
        logFrame.setMaximizable(true);
        logFrame.setResizable(true);
        logFrame.setClosable(true);
        dateChooser.setDate(date);
        JLabel lblDate = new JLabel("Date:");
        lblDate.setForeground(Color.BLUE);

        JScrollPane scrollPane = new JScrollPane(textArea);
        GroupLayout groupLayout = new GroupLayout(logFrame.getContentPane());

        ge = GraphicsEnvironment.getLocalGraphicsEnvironment ();
        String[] fontNames=new String[ge.getAvailableFontFamilyNames().length+1] ;
        fontNames[0]="";
        for(int x = 1; x < ge.getAvailableFontFamilyNames().length-1; x++)
        {
            fontNames[x]=ge.getAvailableFontFamilyNames() [x-1]  ;
        }

        fonts=new JComboBox(fontNames);
        textArea.setFont(new Font("DialogInput", Font.PLAIN, 12));

        JLabel lblFont = new JLabel("Font :");
        lblFont.setForeground(Color.BLUE);

        groupLayout.setHorizontalGroup(
                groupLayout.createParallelGroup(Alignment.TRAILING)
                        .addComponent(urlField, GroupLayout.DEFAULT_SIZE, 492, Short.MAX_VALUE)
                        .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 492, Short.MAX_VALUE)
                        .addGroup(groupLayout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(lblFont)
                                .addGap(16)
                                .addComponent(fonts, GroupLayout.PREFERRED_SIZE, 115, GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(ComponentPlacement.RELATED, 52, Short.MAX_VALUE)
                                .addComponent(refreshOnce)
                                .addGap(18)
                                .addComponent(lblDate)
                                .addGap(27)
                                .addComponent(dateChooser, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                .addGap(41))
        );
        groupLayout.setVerticalGroup(
                groupLayout.createParallelGroup(Alignment.LEADING)
                        .addGroup(groupLayout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
                                        .addComponent(dateChooser, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                        .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
                                                .addComponent(lblDate)
                                                .addComponent(refreshOnce)
                                                .addComponent(fonts, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                                .addComponent(lblFont)))
                                .addGap(32)
                                .addComponent(urlField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(ComponentPlacement.RELATED)
                                .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 391, Short.MAX_VALUE))
        );

        logFrame.getContentPane().setLayout(groupLayout);

        logFrame.getContentPane().add(dateChooser);


        try
        {
            path = ViewTasks.findLogFilePath(task ,job, date);
            fillUrlField(path, urlField);
            fillTextArea(textArea, path);

        } catch (Exception e1)
        {
            JOptionPane.showMessageDialog(null, "Log file could not be found:" + e1.getMessage(), "No log found", JOptionPane.ERROR_MESSAGE);
        }

        dtp.add(logFrame);
        logFrame.setVisible(true);
        logFrame.toFront();
    }

    private void fillUrlField(String path, JTextField urlField)
    {
        urlField.setText("");
        urlField.setText(path);
        urlField.setBackground(Color.LIGHT_GRAY);
        urlField.setColumns(10);
    }


    public void fillTextArea(JTextArea textArea, String path) throws IOException
    {
        textArea.setText("");
        FileInputStream fis = new FileInputStream(path);
        BufferedReader br = new BufferedReader(new InputStreamReader(fis));
        String read;
        while ((read = br.readLine()) != null)
        {

            textArea.append(read);
            textArea.append("\n");

        }
        textArea.setEditable(false);
    }

    public void refreshLog()
    {


        Date newDate = dateChooser.getDate();



        try
        {      String path = ViewTasks.findLogFilePath(task,job, newDate);

            urlField.setText(path);
            urlField.setBackground(Color.LIGHT_GRAY);
            fillTextArea(textArea, path);
            if(!fonts.getSelectedItem().toString().equals(""))
            {textArea.setFont(new Font(fonts.getSelectedItem().toString(), Font.PLAIN, 12));}


        } catch (IOException e1)
        {
            // e1.printStackTrace();
            JOptionPane.showMessageDialog(null, "Log file could not be found " + e1.getMessage(), "No log found", JOptionPane.ERROR_MESSAGE);
        }


    }

}
